package com.ruoyi.graduate.ai;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import org.springframework.stereotype.Component;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.zip.GZIPInputStream;

@Component // 确保Spring能扫描到该Bean
public class TongyiQianwenClient {
    private static final String API_KEY = "sk-e5001887d0ac4ba5bd7b5d7d7676bca9";
    private static final String API_URL = "https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation";

    // 修正：静态main方法测试（不影响Spring Bean）
    public static void main(String[] args) {
        try {
            String response = new TongyiQianwenClient().callQianwenAPI("解释一下量子计算");
            System.out.println("API 响应：\n" + response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 修正：非静态方法，无语法错误
    public String callQianwenAPI(String userInput) throws Exception {
        // 修正笔误：HttpClients.createDefault()
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpPost httpPost = new HttpPost(API_URL);
            httpPost.setHeader("Authorization", "Bearer " + API_KEY);
            httpPost.setHeader("Content-Type", "application/json; charset=UTF-8");
            httpPost.setHeader("Accept", "application/json");
            httpPost.setHeader("Accept-Encoding", "gzip");

            // 构建请求体（无语法错误）
            JSONObject requestBody = new JSONObject();
            requestBody.put("model", "qwen-turbo");
            requestBody.put("input", new JSONObject().put("prompt", userInput));
            JSONObject parameters = new JSONObject();
            parameters.put("temperature", 0.7);
            parameters.put("top_p", 0.8);
            requestBody.put("parameters", parameters);

            byte[] jsonBytes = requestBody.toString().getBytes(StandardCharsets.UTF_8);
            httpPost.setEntity(new ByteArrayEntity(jsonBytes));

            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                int statusCode = response.getStatusLine().getStatusCode();
                HttpEntity entity = response.getEntity();

                if (entity == null) {
                    throw new Exception("API返回空响应，状态码：" + statusCode);
                }

                String result = decompressGzipResponse(entity, response);
                System.out.println("服务器原始响应：" + result);

                JSONObject jsonResponse = new JSONObject(result);
                if (statusCode != 200) {
                    String errorMsg = jsonResponse.optString("message", jsonResponse.optString("error_msg", "未知错误"));
                    throw new Exception("API请求失败，状态码：" + statusCode + "，错误信息：" + errorMsg);
                }

                return jsonResponse.getJSONObject("output").getString("text");
            }
        }
    }

    // 修正：参数类型为HttpEntity（之前可能误写）
    private String decompressGzipResponse(HttpEntity entity, CloseableHttpResponse response) throws Exception {
        String contentEncoding = response.getFirstHeader("Content-Encoding") != null
                ? response.getFirstHeader("Content-Encoding").getValue()
                : "";

        if ("gzip".equals(contentEncoding)) {
            try (InputStream is = entity.getContent();
                 GZIPInputStream gzipIs = new GZIPInputStream(is);
                 ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
                byte[] buffer = new byte[1024];
                int len;
                while ((len = gzipIs.read(buffer)) != -1) {
                    baos.write(buffer, 0, len);
                }
                return baos.toString(StandardCharsets.UTF_8.name());
            }
        } else {
            return EntityUtils.toString(entity, StandardCharsets.UTF_8);
        }
    }
}